#!/usr/bin/python3

import psutil
import time
import pymysql as mysqldb


def main():
    flag = 1

    db = mysqldb.connect(user='root', passwd="123123", host="localhost")
    db.autocommit(True)
    cur = db.cursor()
    shdb = "show databases"
    cur.execute(shdb)
    Tu_db = cur.fetchall()
    for i in Tu_db:
        j = list(i)[0]
        if j == "hu":
            flag = 0
    if flag == 1:
        c_db = "create database hu"
        cur.execute(c_db)
    use_db = "use hu"
    cur.execute(use_db)
    sh_tb = "show tables"
    cur.execute(sh_tb)
    re_sh_tb = cur.fetchall()

    flag = 1
    for i in re_sh_tb:
        j = list(i)[0]
        if j == "zuoye":
            flag = 0

    if flag == 1:
        cr_tb = "create table zuoye(time varchar(30), sent_in int, sent_out int, primary key (time))"
        cur.execute(cr_tb)

    b_sent = psutil.net_io_counters().bytes_sent
    b_recv = psutil.net_io_counters().bytes_recv
    while True:
        time.sleep(1)
        b2_sent = psutil.net_io_counters().bytes_sent
        b2_recv = psutil.net_io_counters().bytes_recv
        a = b2_sent - b_sent
        b = b2_recv - b_recv
        b_sent = b2_sent
        b_recv = b2_recv
        u_time = int(time.time())
        print(u_time, a, b)
        sql = "insert into zuoye(time, sent_in, sent_out) values({u_time},{a},{b})".format(
            u_time=u_time, a=a, b=b)
        cur.execute(sql)

main()